using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using System.Configuration;
using Microsoft.Web.Administration;
using System.DirectoryServices;
using PC.AzureMultiApp.Storage;
using PC.AzureMultiApp.Core;
using System.Threading;
using System.Diagnostics;
using Microsoft.WindowsAzure.Diagnostics.Management;
using PC.AzureMultiApp.Core.Helpers;
using System.IO;
using System.Web;

namespace PC.AzureMultiApp.WebRoleMultiApp
{
    public class WebRole : RoleEntryPoint
    {
        public override bool OnStart()
        {
            CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
            {
                if (RoleEnvironment.IsAvailable)
                    configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));
                else
                    configSetter(ConfigurationManager.AppSettings[configName]);
            });

            ConfigureDiagnostics();

            IISManager.ConfigureIIS();

            StartNotificationService();

            DeployExistingApps();

            return base.OnStart();
        }

        private static void ConfigureDiagnostics()   
        {
            String diagnosticsConnectionString = "Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString";

            CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue(diagnosticsConnectionString)); 
           
            DeploymentDiagnosticManager diagnosticManager =  new DeploymentDiagnosticManager(cloudStorageAccount, RoleEnvironment.DeploymentId); 
            
            RoleInstanceDiagnosticManager roleInstanceDiagnosticManager 
                                                                    = cloudStorageAccount.CreateRoleInstanceDiagnosticManager(  
                                                                            RoleEnvironment.DeploymentId,  
                                                                            RoleEnvironment.CurrentRoleInstance.Role.Name,  
                                                                            RoleEnvironment.CurrentRoleInstance.Id);  
            
            DiagnosticMonitorConfiguration diagnosticMonitorConfiguration = roleInstanceDiagnosticManager.GetCurrentConfiguration();

            diagnosticMonitorConfiguration.Logs.ScheduledTransferPeriod = TimeSpan.FromMinutes(1.0d);
            diagnosticMonitorConfiguration.Logs.ScheduledTransferLogLevelFilter = LogLevel.Verbose;


            // Use 30 seconds for the performance counter sample rate.
            TimeSpan perfSampleRate = TimeSpan.FromSeconds(30.0);

            diagnosticMonitorConfiguration.PerformanceCounters.DataSources.Add(new PerformanceCounterConfiguration()
            {
                CounterSpecifier = @"\Processor(_Total)\% Processor Time",
                SampleRate = perfSampleRate
            });

            diagnosticMonitorConfiguration.PerformanceCounters.DataSources.Add(new PerformanceCounterConfiguration()
            {
                CounterSpecifier = @"\.NET CLR Memory(_Global_)\% Time in GC",
                SampleRate = perfSampleRate
            });

            diagnosticMonitorConfiguration.PerformanceCounters.DataSources.Add(new PerformanceCounterConfiguration()
            {
                CounterSpecifier = @"\Memory\Available Mbytes",
                SampleRate = perfSampleRate
            });

            diagnosticMonitorConfiguration.PerformanceCounters.DataSources.Add(new PerformanceCounterConfiguration()
            {
                CounterSpecifier = @"\ASP.NET\Requests/Sec", 
                SampleRate = perfSampleRate
            });

            diagnosticMonitorConfiguration.PerformanceCounters.DataSources.Add(new PerformanceCounterConfiguration()
            {
                CounterSpecifier = @"\ASP.NET\Requests Rejected",
                SampleRate = perfSampleRate
            });

            // Transfer the counters every 1 minute.
            diagnosticMonitorConfiguration.PerformanceCounters.ScheduledTransferPeriod = TimeSpan.FromMinutes(1.0d);

            diagnosticMonitorConfiguration.WindowsEventLog.DataSources.Add("Application!*");
            diagnosticMonitorConfiguration.WindowsEventLog.DataSources.Add("System!*");
            diagnosticMonitorConfiguration.WindowsEventLog.ScheduledTransferPeriod = TimeSpan.FromMinutes(1d);

            roleInstanceDiagnosticManager.SetCurrentConfiguration(diagnosticMonitorConfiguration);
        }

        private static void StartNotificationService()
        {
            ThreadPool.QueueUserWorkItem(delegate
            {
                try
                {
                    Trace.WriteLine("Open WCF Service to listen notifications", "Information");

                    new DeploymentHostServiceManager();
                    Thread.Sleep(Timeout.Infinite);
                }
                catch (Exception ex)
                {
                    Trace.WriteLine(ex.Message, "Error");
                }
            });
        }

        private static void DeployExistingApps()
        {

            ThreadPool.QueueUserWorkItem(delegate
            {
                Trace.WriteLine("Deploy exiting deployments", "Information");

                DeploymentManager.Deploy();
            });
        }


    }
}
